package com.lagou.protocol.encoder;

import com.lagou.protocol.serializer.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * RPC编码器
 */
public class RpcEncoder extends MessageToByteEncoder {
    /**
     * 目标类
     */
    private Class<?> clazz;

    /**
     * 序列化器
     */
    private Serializer serializer;

    /**
     * 构造编码器
     *
     * @param clazz 目标类
     * @param serializer 序列化器
     */
    public RpcEncoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
    }


    /**
     * 将给定的消息对象编码成二进制
     *
     * @param channelHandlerContext 处理器上下文
     * @param msg 给定的消息对象
     * @param byteBuf 缓冲区
     * @throws Exception
     */
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object msg, ByteBuf byteBuf) throws Exception {
        if (clazz != null && clazz.isInstance(msg)) {
            byte[] bytes = serializer.serialize(msg);
            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
        }
    }
}
